﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Service.Service {

    public class TokenStatisticsService : ServiceBase, ITokenStatisticsService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        public TokenStatisticsService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
            this._iUnitOfWork = iUnitOfWork;
        }

        /// <summary>
        /// 查询用户统计信息(不存在则新增)
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public token_statistics_dto GetOrCreate(long userId) {
            if (!context.TokenStatistics.Exist(o => o.MerchantId == userId)) {//用户统计信息不存在则创建用户统计信息
                TokenStatistics tokenStatistics = new TokenStatistics {
                    MerchantId = userId,
                    Deposit = 0,
                    Depositing = 0,
                    Deposited = 0,
                    BusDeposit = 0,
                    BusDeposited = 0,
                    BusDepositing = 0,
                    FrozenBusProfit = 0,
                    CreateTime = DateTime.Now.ToUnix()
                };
                context.TokenStatistics.Add(tokenStatistics);
                _iUnitOfWork.Commit();
            }
            return context.TokenStatistics.First(o => o.MerchantId == userId).ToDtoObject<token_statistics_dto>();
        }

        public TokenStatistics CreateStatistics(long userId) {
            TokenStatistics tokenStatistics = null;
            if (!context.TokenStatistics.Exist(o => o.MerchantId == userId)) {
                tokenStatistics = new TokenStatistics {
                    MerchantId = userId,
                    Deposit = 0,
                    Depositing = 0,
                    Deposited = 0,
                    BusDeposit = 0,
                    BusDeposited = 0,
                    BusDepositing = 0,
                    FrozenBusProfit = 0,
                    CreateTime = DateTime.Now.ToUnix()
                };
                context.TokenStatistics.Add(tokenStatistics);
            } else {
                tokenStatistics = context.TokenStatistics.FirstOrDefault(c => c.MerchantId == userId);
            }
            return tokenStatistics;
        }
    }
}
